var Promise = require('./es6-promise.min.js');
var baseUrl = 'https://minipd.hderp.cn/api/Api/';
import api from '../appconfig.js';
function wxPromisify(fn) {
    return function (obj = {}) {
        return new Promise((resolve, reject) => {
            obj.success = function (res) {
                resolve(res);
            };
            obj.fail = function (res) {
                reject(res);
            };
            fn(obj);
        });
    };
}

//普通请求
function request(cmd, method, data, callback) {
    // console.log(cmd);
    uni.showLoading({
        title: 'loading'
    });
    wxPromisify(uni.request)({
        url: baseUrl + cmd,
        method: method,
        data: data,
        header: {
            'content-type': 'application/json' // 默认值
        }
    })
        .then(function (res) {
            uni.hideLoading();
            if (res.data.Code == 100) {
                doLogin();
                uni.showToast({
                    icon: 'none',
                    title: '系统繁忙，请刷新重试！'
                });
            } else if (res.data.Code == 0) {
                // console.log(res.data);
                callback(res);
            } else {
                uni.hideLoading();
                uni.showToast({
                    icon: 'none',
                    title: res.data.Message
                });
            }
        })
        .then(function () {
            //执行操作
        });
}
function doLogin() {
    var Fpid = uni.getStorageSync('Fpid');
    // 登录
    var param = {
        Fopenid: uni.getStorageSync('Fopenid'),
        Fpid: null == Fpid ? 0 : Fpid
    };
    uni.showLoading({
        title: 'loading'
    });
    wxPromisify(uni.request)({
        url: baseUrl + 'SpLogin?storeCode=' + api.storecode,
        method: 'post',
        data: param,
        header: {
            'content-type': 'application/json' // 默认值
        }
    })
        .then(function (res) {
            uni.hideLoading();
            uni.setStorageSync('token', res.data.Message);
            uni.setStorageSync('uid', res.data.User.Fid);
            uni.setStorageSync('user', res.data.User);
        })
        .then(function () {
            //执行操作
        });
}

//普通请求
function requestAll(cmd, method, data, callback) {
    uni.showLoading({
        title: 'loading'
    });
    wxPromisify(uni.request)({
        url: baseUrl + cmd,
        method: method,
        data: data,
        header: {
            'content-type': 'application/json' // 默认值
        }
    })
        .then(function (res) {
            uni.hideLoading();
            callback(res);
        })
        .then(function () {
            //执行操作
        });
}
module.exports = {
    baseUrl: baseUrl,
    request: request,
    requestAll: requestAll
};
